package com.jetpack_sunflower.data

import android.content.Context
import androidx.room.*
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.jetpack_sunflower.utils.DATABASE_NAME
import com.jetpack_sunflower.workers.SeedDatabaseWorker

@Database(entities = [Plant::class,GardenPlanting::class], version = 1, exportSchema = false)
@TypeConverters(Converts::class)
abstract class AppDataBase : RoomDatabase() {

    abstract fun getPlantDao(): PlantDao

    abstract fun getGardenPlantingDao(): GardenPlantingDao


    companion object {
        @Volatile
        private var instance: AppDataBase? = null

        fun getInstance(context: Context): AppDataBase {
            return instance ?: synchronized(this) {
                instance ?: buildDataBase(context).also {
                    instance = it
                }
            }
        }

        private fun buildDataBase(context: Context): AppDataBase {
            return Room
                    .databaseBuilder(context, AppDataBase::class.java, DATABASE_NAME)
                    .addCallback(object : RoomDatabase.Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            super.onCreate(db)
                            val requestBuilder = OneTimeWorkRequestBuilder<SeedDatabaseWorker>()
                            WorkManager.getInstance().enqueue(requestBuilder.build())
                        }
                    })
                    .build()

        }
    }
}